package mqtt

import (
	"fmt"
	"github.com/cihub/seelog"
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

const (
	Port = 32000
)

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	seelog.Infof("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	or := client.OptionsReader()
	server := or.Servers()
	seelog.Infof("Connected, %v, %s", server, or.ClientID())
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	or := client.OptionsReader()
	server := or.Servers()
	seelog.Infof("Connect lost: %v %s %v", server, or.ClientID(), err)
}

func NewEmqx(broker string) (mqtt.Client, error) {
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, Port))
	opts.SetClientID(fmt.Sprintf("go_mqtt_client-%s", broker))
	opts.SetUsername("admin")
	opts.SetPassword("208$!456")
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		seelog.Errorf("Connect error: %v", token.Error())
		return nil, fmt.Errorf("Connect error: %s %v", broker, token.Error())
	}

	return client, nil
}

func Sub(client mqtt.Client, handler mqtt.MessageHandler) {
	topic := "file_transfer_finish"
	token := client.Subscribe(topic, 1, handler)
	token.Wait()
	seelog.Infof("Subscribed to topic: %s", topic)
}
